import {formatGMTDate} from '../../../../assets/js/util.js'
import details from './datils.vue'
import advance from './advancedFilter.vue'
import echarts from 'echarts'
export default {
	data() {
		return {
			//菜单索引
			navDefault: '0',
			// 默认参数 和 URL
			SRC: '',
			DP: {
				p: '',
				f: ''
			},
			// title
			title: "实时国家概况",
			/* 的宽*/
			pageWidth: '100%',
			// 选择的时间
			date: '',
			// 对比时间
			cdate: '',
			// details 展示数据
			datas: [],
			// 渠道数组
			countries: [],
			// 服务器数组
			servers: [],
			// 请求的参数
			//
			postObj: {
				'date': '2017-05-25',
				'cdate': '2017-05-24',
				'countryid': '',
				'serverid': '0'
			},
			// 整体实时在线
			real: {
				tooltip: {
					trigger: 'axis'
				},
				legend: {
					top: '10px',
					data: ['', '', '']
				},
				grid: {
					left: '0%',
					right: '1%',
					bottom: '15%',
					containLabel: true
				},
				toolbox: {
					right: '20',
					feature: {
						dataZoom: {
							yAxisIndex: 'none'
						},
						magicType: {
							type: ['line', 'bar']
						},
						restore: {},
						saveAsImage: {}
					}
				},
				xAxis: {
					type: 'category',
					boundaryGap: false,
					data: [],
					axisLabel:{
                        interval:10,
                        rotate:45,//倾斜度 -90 至 90 默认为0
                        margin:20,
                    },
				},
				yAxis: {
					type: 'value',
					// max: 10000
				},
				dataZoom: [{
					handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
					handleSize: '80%',
					handleStyle: {
						color: '#fff',
						shadowBlur: 3,
						shadowColor: 'rgba(0, 0, 0, 0.6)',
						shadowOffsetX: 2,
						shadowOffsetY: 2
					}
				}],
				series: [{
					name: '1',
					type: 'line',
					showSymbol: false,
					data: []
				}, {
					name: '2',
					type: 'line',
					showSymbol: false,
					data: []
				}, {
					name: '3',
					type: 'line',
					showSymbol: false,
					data: []
				}]
			},
			// 实时数据显示
			realLoadShow:true,
			// 表格数据
			tableData: [],
			tabelHead: [
				{prop:"hour",label:"日期"},
				{prop:"newUserLookValue",label:"新增账号数-查看日期"},
		        {prop:"newUserCompareValue",label:"新增账号数-对比日期"},
		        {prop:"userSecond2LeftHourLookValue",label:"累计实时次留-查看日期"},
		        {prop:"userSecond2LeftHourCompareValue",label:"累计实时次留-对比日期"},
		        {prop:"payLookValue",label:"付费金额(￥)-查看日期"},
		        {prop:"payCompareValue",label:"付费金额(￥)-对比日期"}
			],
			// 分小时数据 付费金额
			pay: {
				tooltip: {
					trigger: 'axis'
				},
				legend: {
					top: '10px',
					data:[{
			            name: '',
			        },{
			            name: '',
			        },{
			            name: '',
			        }]
				},
				grid: {
					left: '0%',
					right: '1%',
					bottom: '15%',
					containLabel: true
				},
				toolbox: {
					right: '20',
					feature: {
						dataZoom: {
							yAxisIndex: 'none'
						},
						magicType: {
							type: ['line', 'bar']
						},
						restore: {},
						saveAsImage: {}
					}
				},
				xAxis: {
					type: 'category',
					boundaryGap: false,
					data: [],
					axisLabel:{
                        margin:20,
                    },
				},
				yAxis: {
					type: 'value',
					// max: 10000
				},
				dataZoom: [{
					handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
					handleSize: '80%',
					handleStyle: {
						color: '#fff',
						shadowBlur: 3,
						shadowColor: 'rgba(0, 0, 0, 0.6)',
						shadowOffsetX: 2,
						shadowOffsetY: 2
					}
				}],
				series: [{
					name: '1',
					type: 'line',
					smooth: true,
					data: [],
					symbol:'circle',
				}, {
					name: '2',
					type: 'line',
					smooth: true,
					data: [],
					symbol:'roundRect',
				}, {
					name: '3',
					type: 'line',
					smooth: true,
					data: [],
					symbol:'triangle',
				}]
			},
			// 点击查看分小时详细数据 表格数据
			tableData2:[],
			tabelHead2: [
				{prop:"hour",label:"日期"},
				{prop:"newUserLookValue",label:"新增账号数-查看日期"},
		        {prop:"newUserCompareValue",label:"新增账号数-对比日期"},
		        {prop:"payUserLookValue",label:"付费账号数-查看日期"},
		        {prop:"payUserCompareValue",label:"付费账号数-对比日期"},
		        {prop:"payLookValue",label:"付费金额(￥)-查看日期"},
		        {prop:"payCompareValue",label:"付费金额(￥)-对比日期"},
		        {prop:"newPayUserLookValue",label:"新增账号付费人数-查看日期"},
		        {prop:"newPayUserCompareValue",label:"新增账号付费人数-对比日期"},
		        {prop:"newUserPayLookValue",label:"新增账号付费金额(￥)-查看日期"},
		        {prop:"newUserPayCompareValue",label:"新增账号付费金额(￥)-对比日期"},
			],
		}
	},
	methods: {
		// 设置图表初始化宽度
		chartsWidth (el){
			if(document.getElementById(el)!==null){
				document.getElementById(el).style.width = window.innerWidth-290+"px";
			}
		},
		//初始化
		_init() {
			var arr = ['newAccount','payMoney','account','id','pay','person','money'];
			for(var x=0; x<arr.length;x++){
				this.chartsWidth(arr[x]);
				this[arr[x]+'Charts'] = echarts.init(document.getElementById(arr[x]));
				this[arr[x]+'Charts'].setOption(this.pay);
			}
			window.addEventListener('resize', function() {
				for(var i in arr){
					this.chartsWidth(arr[i])
				}
				/*var resizeArr = ['realTimeDataChart','newAccountCharts','payMoneyCharts','accountCharts','idCharts','payCharts','personCharts','moneyCharts']*/
				var resizeArr = ['newAccountCharts','payMoneyCharts','accountCharts','idCharts','payCharts','personCharts','moneyCharts']
				for(var j in resizeArr){
					this[resizeArr[j]].resize();
				}
			}.bind(this))
		},
		// 通用 成功 与 失败
		successFun(data) {
			this.$message({
				message: data,
				type: 'success'
			});
		},
		errorFun(data) {
			this.$message.error(data);
		},
		// 选择时间
		dateChange(val) {
			if (val === undefined) {
				this.errorFun('请选择查看时间！')
			} else {
				this.date = val;
				this.postObj.date = val;
			}
			if(this.postObj.countryid !== ""){
				this.getData(this.postObj);
			}
		},
		// 对比时间
		cdateChange(val) {
			if (val === undefined) {
				this.errorFun('请选择对比时间！')
			} else {
				this.cdate = val;
				this.postObj.cdate = val;
			}
			if(this.postObj.countryid !== ""){
				this.getData(this.postObj);
			}
		},
		// 选择游戏的平台
		handleSelect(key, keyPath) {
			if (key === '4') {
				this.$refs.advance.filterShow = true;
			} else {
				this.postObj['platformid'] = key;
				this.postObj['serverid'] = '0';
				this.postObj['channelid'] = '0';
				this.getData(this.postObj);
			}
		},
		// 内容框的排序
		detailsSort(data) {
			var dataCp = data;
			var arr = ['新增账号数', '活跃账号数', '付费金额(￥)', '活跃付费率', '活跃ARPU(￥)', '付费ARPU(￥)', '昨日新增帐号次留', '前日新增帐号三日留'];
			for (var i = 0; i < data.length; i++) {
				for (var j in data[i]) {
					switch (data[i][j]) {
						case arr[0]:
							dataCp[0] = data[i];
							break;
						case arr[1]:
							dataCp[1] = data[i];
							break;
						case arr[2]:
							dataCp[2] = data[i];
							break;
						case arr[3]:
							dataCp[3] = data[i];
							break;
						case arr[4]:
							dataCp[4] = data[i];
							break;
						case arr[5]:
							dataCp[5] = data[i];
							break;
						case arr[6]:
							dataCp[6] = data[i];
							break;
						case arr[7]:
							dataCp[7] = data[i];
							break;
					}
				}
			}
			this.datas = dataCp;
		},
		// 获取后台数据
		getData(data) {
			var that = this;
			/*`${that.SRC}overviewCountry/search.do`, data,{emulateJSON:true}*/
			/*'date': '2017-05-25',
				'cdate': '2017-05-24',
				'countryid': '',
				'serverid': '0'*/
			var p = new Promise(function(resolve, reject) {
				that.$http.jsonp(`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=search`,{
					params: {
						'ps': `date=${data.date}&cdate=${data.cdate}&countryid=${data.countryid}&serverid=${data.serverid}`
					}
				}).then(function(res) {
					resolve(res.body)
				})
			})
			p.then(function(value) {
				var data = JSON.parse(value)
				data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
				if (parseInt(data["res"]) === 0) {
					that.detailsSort(data["datas"]);
					that.echartsData(data);
					that.tableConfig(data['detailDatas1']);
					that.tableConfig2(data['detailDatas']);
				} else {
					that.errorFun(data['msg']);
				}
			})
		},
		// 获取服务器list 平台list  服务器list
		getList() {
			var that = this;
			var pushData = function(pushArr, attr, data) {
				that[pushArr] = [];
				for (var i in data[attr]) {
					that[pushArr].push({
						value: i,
						label: data[attr][i]
					})
				}
			};
			this.$http.jsonp(`${this.SRC}data/get.do`,{params:{
				p:this.DP.p,
				f:this.DP.f,
				a:"initParam",
				ps: ""
			}}).then(function(res) {
				var data = JSON.parse(JSON.parse(res.body));
				if (parseInt(data["res"]) === 0) {
					// 后台select的数据
					var lists = ["serverItmes", "countryItems"];
					// 页面select名字
					var nameLists = ["servers", "countries"];
					for (var i = 0; i < lists.length; i++) {
						if (data[lists[i]] !== undefined) {
							pushData(nameLists[i], lists[i], data);
						}
					}
					that.postObj.countryid = that.countries[0]["label"];
					that.getData(that.postObj);
				} else {
					this.getErrorMsg(Number(data.res))
				}
			})
		},
		// 改变表数据
		echartsData(d) {
			this.realLoadShow = false;
			// 删除零的元素
			function removeZero(arr){
				var date = new Date();
				if(arr.length>25){
					for (var i =0; i<arr.length; i++){
						if(arr[i] === 0 && i>date.getHours()*11){
							arr[i] = '-'
						}
					}
				}else{
					/*for (var i =0; i<arr.length; i++){
						if(arr[i] === 0 && i>date.getHours()){
							arr[i] = '-'
						}
					}*/
				}
				return arr;
			}
			// 实时数据获取到数据渲染
			/*var data = d['onlineRealTimeChart']['jsonStr'];
			this.realTimeDataChart.setOption({
				legend: {
					data: data['names']
				},
				xAxis: {
					data: data.columnkeys
				},
				series: [
					{
						name: data.names[0],
						data: data.data[0]
					},
					{
						name: data.names[1],
						data: data.data[1]
					},
					{
						name: data.names[2],
						data: removeZero(data.data[2])
					}
				]
			});*/

			//  分小时累计数据 新增账号数获取到数据渲染
			var account = d['lineChart21']['jsonStr'];
			//  将数字转换为日期
			function dateStr(arr) {
				var arrN = [];
				for(var i=0; i<arr.length; i++){
					if(i<10){
						var date = '0' + arr[i] + ':00';
					}else{
						var date = arr[i] + ':00';
					}
					arrN.push(date)
				}
				return arrN;
			}
			this.newAccountCharts.setOption({
				legend: {
					data: account.names
				},
				xAxis: {
					data: dateStr(account.columnkeys)
				},
				series: [
					{
						name: account.names[0],
						data: removeZero(account.data[0])
					},
					{
						name: account.names[1],
						data: account.data[1]
					},
					{
						name: account.names[1],
						data: account.data[1]
					}
				]
			});

			// 分小时累计数据 付费金额(￥)获取到数据渲染
			var payMoney = d['lineChart51']['jsonStr'];
			this.payMoneyCharts.setOption({
				legend: {
					data: payMoney.names
				},
				xAxis: {
					data: dateStr(payMoney.columnkeys)
				},
				series: [
					{
						name: payMoney.names[0],
						data: removeZero(payMoney.data[0])
					},
					{
						name: payMoney.names[1],
						data: payMoney.data[1]
					},
					{
						name: payMoney.names[2],
						data: payMoney.data[2]
					}
				]
			});

			//分小时数据  新增账号数 获取到数据渲染
			var acc = d['lineChart2']['jsonStr'];
			this.accountCharts.setOption({
				legend: {
					data: acc.names
				},
				xAxis: {
					data: dateStr(acc.columnkeys)
				},
				series: [
					{
						name: acc.names[0],
						data: removeZero(acc.data[0])
					},
					{
						name: acc.names[1],
						data: acc.data[1]
					},
					{
						name: acc.names[2],
						data: acc.data[2]
					}
				]
			});

			//分小时数据  付费账号数 获取到数据渲染
			var id = d['lineChart4']['jsonStr'];
			this.idCharts.setOption({
				legend: {
					data: id.names
				},
				xAxis: {
					data: dateStr(id.columnkeys)
				},
				series: [
					{
						name: id.names[0],
						data: removeZero(id.data[0])
					},
					{
						name: id.names[1],
						data: id.data[1]
					},
					{
						name: id.names[2],
						data: id.data[2]
					}
				]
			});

			//分小时数据  付费金额 获取到数据渲染
			var pay = d['lineChart5']['jsonStr'];
			this.payCharts.setOption({
				legend: {
					data: pay.names
				},
				xAxis: {
					data: dateStr(pay.columnkeys)
				},
				series: [
					{
						name: pay.names[0],
						data: removeZero(pay.data[0])
					},
					{
						name: pay.names[1],
						data: pay.data[1]
					},
					{
						name: pay.names[2],
						data: pay.data[2]
					}
				]
			});

			//分小时数据  新增账号付费人数 获取到数据渲染
			var person = d['lineChart6']['jsonStr'];
			this.personCharts.setOption({
				legend: {
					data: person.names
				},
				xAxis: {
					data: dateStr(person.columnkeys)
				},
				series: [
					{
						name: person.names[0],
						data: removeZero(person.data[0])
					},
					{
						name: person.names[1],
						data: person.data[1]
					},
					{
						name: person.names[2],
						data: person.data[2]
					}
				]
			});

			//分小时数据  新增账号付费人数 获取到数据渲染
			var money = d['lineChart7']['jsonStr'];
			this.moneyCharts.setOption({
				legend: {
					data: money.names
				},
				xAxis: {
					data: dateStr(money.columnkeys)
				},
				series: [
					{
						name: money.names[0],
						data: removeZero(money.data[0])
					},
					{
						name: money.names[1],
						data: money.data[1]
					},
					{
						name: money.names[2],
						data: money.data[2]
					}
				]
			});
		},
		//表格数据时间优化
		tableConfig(data) {
			for(var i in data){
				if(i<10){
					data[i]['hour'] = '0' + data[i]['hour'] + ':00 ~ ' + '0' + data[i]['hour'] + ":59";
				}else{
					data[i]['hour'] = data[i]['hour'] + ':00 ~ ' + data[i]['hour'] + ":59";
				}
				data[i]["userSecond2LeftHourCompareValue"] =(data[i]["userSecond2LeftHourCompareValue"]*100).toFixed(2);
			}
			this.tableData = data;
		},
		//点击查看分小时详细数据 表格数据时间优化
		tableConfig2(data) {
			for(var i in data){
				if(i<10){
					data[i]['hour'] = '0' + data[i]['hour'] + ':00 ~ ' + '0' + data[i]['hour'] + ":59";
				}else{
					data[i]['hour'] = data[i]['hour'] + ':00 ~ ' + data[i]['hour'] + ":59";
				}
			}
			this.tableData2 = data;
		},
		// 每隔15秒一次
		setTimeOnline() {
			var that = this;
			setInterval(function(){
				// that.getData(that.postObj);
			},15000);
		},
		// 表格下载
	    excel(tableIndex,sheet) {
	      	this.downloadExl(this['tabelHead'+tableIndex],this['tableData'+tableIndex],sheet,sheet);
	    }
	},
	components: {
		'v-details': details,
		'v-advance': advance,
	},
	computed:{
		xlsx(){
		  return this.title+'.xlsx'
		}
	},
	mounted() {
		// 初始化URL
		this.SRC = this.$store.getters.src;
		this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
		this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
		// 初始化时间
		this.date = new Date();
		this.cdate = new Date(new Date().getTime() - 86400000);
		this.postObj.date = formatGMTDate(new Date(), true);
		this.postObj.cdate = formatGMTDate(new Date().getTime() - 86400000, true);

		// 获取到服务器 平台 渠道 list
		// 实时数据
		this.getList();
		// this.realTimeDataChart= echarts.init(document.getElementById('realTimeData'));
      	// this.realTimeDataChart.setOption(this.real);
      	this._init();
      	

      	setTimeout(this.setTimeOnline,15000);
	}
}